package ru.beta2.testyard.config.defaults;

import ru.beta2.testyard.config.SerializationHandler;

import java.io.*;
import java.nio.ByteBuffer;

/**
 * Default {@link ru.beta2.testyard.config.SerializationHandler} implementation based on standart java serialization.
 * <br/>
 * Not tested by framework developers because we used Hessian protocol for serialization.
 * <br/>
 * User: Inc
 * Date: 18.01.2009
 * Time: 14:38:02
 */
public class DefaultSerializationHandler implements SerializationHandler
{
    public Object readObject(final ByteBuffer buf) throws IOException
    {
        ObjectInputStream in = new ObjectInputStream(
                new InputStream() {
                    public int read() throws IOException {
                        if (!buf.hasRemaining()) {
                            return -1;
                        }
                        return buf.get();
                    }

                    public int read(byte[] bytes, int off, int len) throws IOException {
                        // Read only what's left
                        len = Math.min(len, buf.remaining());
                        buf.get(bytes, off, len);
                        return len;
                    }
                }
        );
        try {
            return in.readObject();
        }
        catch (ClassNotFoundException e) {
            throw new RuntimeException("Class not found during read object from byte buffer", e);
        }
    }

    public ByteBuffer writeObject(Object object) throws IOException
    {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(os);
        out.writeObject(object);
        out.flush();
        byte[] ba = os.toByteArray();
        ByteBuffer bb = ByteBuffer.allocate(ba.length);
        bb.put(ba);
        bb.rewind();
        return bb;
    }
}
